package com.rpc.center.event.listener;


import com.rpc.center.entity.ConsumerNode;
import com.rpc.center.entity.PublisherNode;
import com.rpc.center.event.eventtype.DiscoverEvent;
import com.rpc.center.manager.RPCServiceManager;
import com.rpc.common.entity.request.DiscoverDTO;
import com.rpc.common.entity.response.DiscoverRS;
import com.rpc.center.event.eventtype.EventType;
import com.rpc.common.entity.HostInfoPair;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DiscoverListener extends EventListener<DiscoverEvent> {
    @Autowired
    private RPCServiceManager serviceManager;
    @Override
    public void actionListener(DiscoverEvent event) {
        DiscoverDTO discoverDTO = event.getMessage();
        Channel channel=event.getChannel();
        String serviceID = discoverDTO.getInterfaceName() + discoverDTO.getVersion();
        DiscoverRS discoverRS = new DiscoverRS();
        discoverRS.setSuccess(true);
        List<PublisherNode> result=serviceManager.searchService(serviceID);  //服务查找
        System.out.println("查找到"+result.size()+"条数据");
        List<HostInfoPair> addressList=new ArrayList<>();
        for(PublisherNode node:result){
            HostInfoPair infoPair=new HostInfoPair(node.getAddress(),node.getPort());
            addressList.add(infoPair);
        }
        discoverRS.setServerAddressList(addressList);
        discoverRS.setSuccess(true);
        discoverRS.setMsg("查询服务成功");
        channel.writeAndFlush(discoverRS);
        ConsumerNode consumerNode=new ConsumerNode();
        consumerNode.setAddress(channel.remoteAddress().toString());
        consumerNode.setChannel(channel);
        consumerNode.setSubscribeServiceID(serviceID);
        //添加到订阅列表中
        serviceManager.addSubscriber(serviceID,consumerNode);
    }

    public DiscoverListener() {
        this.setEventType(EventType.DISCOVER_EVENT);
    }
}
